/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.slice.imageview.preview.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.app.Context;
import ohos.media.common.Source;
import ohos.media.player.Player;
import ohos.net.NetCapabilities;
import ohos.net.NetManager;

import com.xuexiang.xui_lib.util.LogUtils;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.util.ToastUtil;

/**
 * 视频播放类
 *
 * @since 2021-04-16
 */
public class VideoPlayerSlice extends AbilitySlice {
    private String TAG = "VideoPlayerSlice";
    private static Player mPlayer;
    private SurfaceProvider mSurfaceProvider;
    private DependentLayout mLayout;
    private String mUrl;
    private Source source;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_video_play);
        if (intent != null) {
            mUrl = intent.getStringParam("url");
        }
        initSurfaceProvider();
    }

    @Override

    protected void onActive() {
        super.onActive();
        if (source == null) {
            initSurfaceProvider();
        }
    }

    private void playUrl(Surface surface) {

        try {
            if(mUrl!=null) {
                source = new Source(mUrl);
                mPlayer.setSource(source);

                mPlayer.setVideoSurface(surface);

                mPlayer.setPlayerCallback(new VideoPlayerCallback());

                mPlayer.prepare();

                mSurfaceProvider.setTop(0);

                mPlayer.play();
            }else{
                return;
            }

        } catch (Exception e) {
            LogUtils.info(TAG, "playUrl Exception:" + e.getMessage());

        }

    }


    private void initSurfaceProvider() {
        mLayout = (DependentLayout) findComponentById(ResourceTable.Id_video_player_dl);
        mPlayer = new Player(this);
        mSurfaceProvider = new SurfaceProvider(this);
        mSurfaceProvider.getSurfaceOps().get().addCallback(new VideoSurfaceCallback());
        mSurfaceProvider.pinToZTop(true);
        mSurfaceProvider.setMarginsTopAndBottom(600, 600);
        mLayout.addComponent(mSurfaceProvider);
        mLayout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });
    }

    /**
     * 视频渲染回调
     *
     * @since 2021-04-16
     */
    class VideoSurfaceCallback implements SurfaceOps.Callback {


        @Override

        public void surfaceCreated(SurfaceOps surfaceOps) {
            LogUtils.info(TAG, "surfaceCreated() called.");
            if (mSurfaceProvider.getSurfaceOps().isPresent()) {
                Surface surface = mSurfaceProvider.getSurfaceOps().get().getSurface();
                if(VideoPlayerSlice.isNetworkAvailable(getContext())) {
                    playUrl(surface);
                }else {
                    ToastUtil.showToast(getContext(),"网络信号差");
                }
            }

        }


        @Override

        public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
            LogUtils.info(TAG, "surfaceChanged() called.");
        }


        @Override

        public void surfaceDestroyed(SurfaceOps surfaceOps) {
            LogUtils.info(TAG, "surfaceDestroyed() called.");
        }

    }


    private class VideoPlayerCallback implements Player.IPlayerCallback {


        @Override

        public void onPrepared() {
            LogUtils.info(TAG, "onPrepared");

        }


        @Override

        public void onMessage(int i, int i1) {
            LogUtils.info(TAG, "onMessage");

        }


        @Override

        public void onError(int i, int i1) {
            LogUtils.info(TAG, "onError: i=" + i + ", i1=" + i1);

        }


        @Override

        public void onResolutionChanged(int i, int i1) {
            LogUtils.info(TAG, "onResolutionChanged");

        }


        @Override

        public void onPlayBackComplete() {
            LogUtils.info(TAG, "onPlayBackComplete");

            if (mPlayer != null) {
                mPlayer.pause();
                mPlayer = null;

            }

        }

        @Override

        public void onRewindToComplete() {
            LogUtils.info(TAG, "onRewindToComplete");

        }


        @Override

        public void onBufferingChange(int i) {
            LogUtils.info(TAG, "onBufferingChange");

        }


        @Override

        public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
            LogUtils.info(TAG, "onNewTimedMetaData");

        }


        @Override

        public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
            LogUtils.info(TAG, "onMediaTimeIncontinuity");

        }

    }

    @Override
    protected void onStop() {
        stopPlayback();
        super.onStop();
    }

    /**
     * 停止播放
     *
     * @since 2021-04-16
     */
    public void stopPlayback() {
        if (mPlayer != null) {
            mPlayer.pause();
            mPlayer.release();
            mPlayer = null;
        }
    }
    /**
     * 网络是否可用
     *
     * @param context context
     * @return isNetworkAvailable isNetworkAvailable
     */
    public static boolean isNetworkAvailable(Context context) {
        NetManager netManager = NetManager.getInstance(context);
        boolean connected;
        if (netManager.hasDefaultNet() && netManager.getDefaultNet() != null) {
            NetCapabilities capabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
            connected = capabilities.hasBearer(NetCapabilities.BEARER_WIFI) || capabilities.hasBearer(NetCapabilities.BEARER_CELLULAR);
        } else {
            connected = false;
        }
        return connected;
    }
}

